package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.StringUtils;
import com.share.device.domain.Region;
import com.share.device.mapper.RegionMapper;
import com.share.device.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {

    @Autowired
    private RegionMapper regionMapper;

    //根据上级code获取下级数据列表
    @Override
    public List<Region> selectByParentCode(String parentCode) {

        List<Region> regionList = regionMapper.selectByParentCode(parentCode);

        if (regionList.isEmpty()){
            throw new ServiceException("无下级地区");
        }

        //设置hasNext字段 如果当前地区有下一级地区为true，否则为false，例如四川则为true，成华区则为false
        for (Region region : regionList) {

            //使用mp 用当前地区的code作为parentCode去查询，如果为0则没有下级地区，否则有下级地区
            Long count = regionMapper.selectCount(new LambdaQueryWrapper<Region>()
                    .eq(Region::getParentCode, region.getCode()));

            if(count == 0){
                //为0则没有下级地区
                region.setHasChildren(false);
            }else {
                //有下级地区
                region.setHasChildren(true);
            }
        }

        return regionList;
    }

    //根据地区编号 获取对应地区的名称
    @Override
    public String getNameByCode(String code) {

        if(StringUtils.isEmpty(code)){
            return "";
        }

        //使用mp 查询对应code的地区名称
        Region region = regionMapper.selectOne(new LambdaQueryWrapper<Region>()
                .eq(Region::getCode, code));

        if (region!=null) return region.getName();

        return "";
    }
}
